<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>腾途旅途乐</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }

        .container {
            text-align: center;
            max-width: 600px;
            padding: 20px 20px;
        }

        .logo {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 10px;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .title {
            font-size: 2rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }

        .subtitle {
            font-size: 1rem;
            margin-bottom: 20px;
            opacity: 0.9;
        }

        .features {
            display: flex;
            justify-content: space-around;
            margin-bottom: 20px;
        }

        .feature {
            text-align: center;
            padding: 10px;
        }

        .feature-icon {
            font-size: 2rem;
            margin-bottom: 5px;
        }

        .feature-text {
            font-size: 0.9rem;
            opacity: 0.9;
        }

        .notice-box {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 15px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }

        .notice-title {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .notice-content {
            font-size: 0.95rem;
            line-height: 1.6;
            opacity: 0.95;
        }

        .notice-content .highlight {
            color: #ffd700;
            font-weight: bold;
        }

        .steps {
            margin: 15px 0;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 15px;
        }

        .steps-title {
            font-size: 1rem;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .step-item {
            display: flex;
            align-items: center;
            margin: 8px 0;
            padding: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
        }

        .step-number {
            width: 28px;
            height: 28px;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 0.9rem;
            margin-right: 10px;
            flex-shrink: 0;
        }

        .step-text {
            font-size: 0.9rem;
            text-align: left;
        }

        .btn {
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
            color: white;
            border: none;
            padding: 12px 35px;
            font-size: 1.1rem;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }

        .btn:hover {
            transform: translateY(-2px) scale(1.05);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
            animation: none;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            animation: none;
        }

        .highlight-tip {
            background: rgba(255, 215, 0, 0.2);
            border: 1px solid rgba(255, 215, 0, 0.5);
            border-radius: 10px;
            padding: 10px;
            margin: 15px 0;
            font-size: 0.9rem;
        }

        .status {
            margin-top: 15px;
            padding: 12px;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
        }

        .status.success {
            background: rgba(76, 175, 80, 0.3);
        }

        .status.error {
            background: rgba(244, 67, 54, 0.3);
        }

        .footer {
            margin-top: 20px;
            opacity: 0.7;
            font-size: 0.85rem;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 15px 15px;
            }

            .title {
                font-size: 1.8rem;
            }

            .subtitle {
                font-size: 0.95rem;
            }

            .notice-box {
                padding: 15px;
            }

            .notice-title {
                font-size: 1rem;
            }

            .notice-content {
                font-size: 0.9rem;
            }

            .steps {
                padding: 12px;
            }

            .step-item {
                padding: 6px;
            }

            .step-number {
                width: 26px;
                height: 26px;
                font-size: 0.85rem;
                margin-right: 8px;
            }

            .step-text {
                font-size: 0.85rem;
            }

            .features {
                flex-direction: row;
                gap: 8px;
            }

            .feature {
                padding: 8px 8px;
            }

            .feature-icon {
                font-size: 1.8rem;
            }

            .feature-text {
                font-size: 0.8rem;
            }

            .btn {
                padding: 10px 25px;
                font-size: 1rem;
                width: 100%;
            }

            .footer {
                font-size: 0.8rem;
                margin-top: 15px;
            }
        }

        @media (max-width: 480px) {
            .logo {
                font-size: 2rem;
            }

            .title {
                font-size: 1.5rem;
            }

            .subtitle {
                font-size: 0.85rem;
            }

            .features {
                gap: 5px;
            }

            .feature {
                padding: 8px 5px;
            }

            .feature-icon {
                font-size: 1.5rem;
            }

            .feature-text {
                font-size: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">免费WiFi认证</h1>
        <p class="subtitle">观看广告即可畅享高速网络</p>
        
        <!-- 重要提示 -->
        <div class="notice-box" th:if="${!isLimited}">
            <div class="notice-title">
                <span>💡</span>
                <span>温馨提示</span>
            </div>
            <div class="notice-content">
                您当前已连接WiFi,目前可临时上网 <span class="highlight">3分钟</span>。<br>
                点击下方按钮进入小程序观看广告，即可获得 <span class="highlight">60分钟</span> 免费上网时长！
            </div>
        </div>

        <!-- 防刷限制提示 -->
        <div class="notice-box" th:if="${isLimited}" style="background: rgba(255, 82, 82, 0.25); border-color: rgba(255, 82, 82, 0.5);">
            <div class="notice-title">
                <span>🚫</span>
                <span>访问受限</span>
            </div>
            <div class="notice-content">
                您在短时间内已多次使用临时上网，系统检测到异常行为。<br>
                为保障网络资源公平使用，您需要等待 <span class="highlight" th:text="${banDuration}">30</span> 分钟后才能继续使用临时上网功能。<br>
                <br>
                💡 建议：请通过观看广告获取正常上网权限，享受更长的上网时长！
            </div>
        </div>

        <!-- 使用步骤 -->
        <div class="steps">
            <div class="steps-title">📋 使用步骤</div>
            <div class="step-item">
                <div class="step-number">1</div>
                <div class="step-text">点击下方按钮进入微信小程序</div>
            </div>
            <div class="step-item">
                <div class="step-number">2</div>
                <div class="step-text">观看15-30秒的激励视频广告</div>
            </div>
            <div class="step-item">
                <div class="step-number">3</div>
                <div class="step-text">广告播放完成后自动认证</div>
            </div>
            <div class="step-item">
                <div class="step-number">4</div>
                <div class="step-text">畅享60分钟免费高速WiFi</div>
            </div>
        </div>

        <button id="startBtn" class="btn" th:disabled="${isLimited}" onclick="handleStart()">
            <span th:if="${!isLimited}">🚀 进入小程序观看广告</span>
            <span th:if="${isLimited}">⏰ 暂时无法使用</span>
        </button>
        
        <div class="features">
            <div class="feature">
                <div class="feature-icon">⚡</div>
                <div class="feature-text">高速稳定</div>
            </div>
            <div class="feature">
                <div class="feature-icon">🎬</div>
                <div class="feature-text">观看广告</div>
            </div>
            <div class="feature">
                <div class="feature-icon">🎉</div>
                <div class="feature-text">免费上网</div>
            </div>
        </div>
        
        <div id="status" class="status" style="display: none;">
            <div id="statusText">正在处理中...</div>
        </div>

        <div class="footer">
            <p>💡 小贴士：广告时长约15-30秒，不消耗您的流量</p>
            <p style="margin-top: 10px;">© 2025 免费WiFi服务平台 · 安全 · 便捷 · 免费</p>
        </div>
    </div>

    <script th:inline="javascript">
        // 解析URL参数
        function getUrlParams() {
            const params = {};
            const urlSearchParams = new URLSearchParams(window.location.search);
            for (const [key, value] of urlSearchParams) {
                params[key] = value;
            }
            return params;
        }

        // 显示状态信息
        function showStatus(text, type = 'info') {
            const statusDiv = document.getElementById('status');
            const statusText = document.getElementById('statusText');
            
            statusDiv.style.display = 'block';
            statusText.innerHTML = text;
            
            statusDiv.className = 'status';
            if (type === 'success') {
                statusDiv.classList.add('success');
            } else if (type === 'error') {
                statusDiv.classList.add('error');
            }
        }

        // 显示加载状态
        function showLoading(text) {
            showStatus('<span class="loading"></span>' + text);
        }

        // 保存访问参数到后端
        async function saveAccessParams() {
            try {
                const params = getUrlParams();
                console.log('URL参数:', params);

                // 构建要保存的数据
                const data = {
                    src: params.src,
                    macAddress: params.macAddress,
                    deviceId: params.deviceId,
                    channelId: params.channelId,
                    vendorTimestamp: params.timestamp ? parseInt(params.timestamp) : null,
                    sign: params.sign,
                    signVer: params.sign_ver
                };

                // 过滤掉空值
                Object.keys(data).forEach(key => {
                    if (data[key] === undefined || data[key] === null || data[key] === '') {
                        delete data[key];
                    }
                });

                console.log('要保存的数据:', data);

                // 调用后端API
                const response = await fetch('/prod-api/wifi/guide/save', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();
                console.log('保存结果:', result);

                if (result.code === 200) {
                    showStatus('参数保存成功！正在打开小程序...', 'success');
                    // 延迟1秒后打开小程序
                    setTimeout(() => {
                        openMiniProgram();
                    }, 1000);
                } else {
                    showStatus('参数保存失败: ' + (result.msg || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('保存参数时发生错误:', error);
                showStatus('网络请求失败，请检查网络连接', 'error');
            }
        }

        // 打开微信小程序
        function openMiniProgram() {
            const appId = 'wx954826de37d5c792';
            
            // uni-app编译后的小程序路径
            const path = 'pages/index';
            const envVersion = 'develop'; // release: 正式版, trial: 体验版, develop: 开发版
            
            // 获取当前页面的URL参数
            const params = getUrlParams();
            console.log('【H5页面】获取到的URL参数:', params);
            
            // 验证必要参数
            if (!params.deviceId) {
                console.error('❌ 缺少必要参数：deviceId');
                showStatus('❌ 缺少设备ID参数，无法打开小程序', 'error');
                return;
            }
            
            if (!params.macAddress) {
                console.warn('⚠️ 缺少MAC地址参数');
            }
            
            // 构建query字符串（传递给小程序的参数）
            // 注意：需要对每个参数的值进行URL编码
            const queryParams = [];
            if (params.src) queryParams.push(`src=${encodeURIComponent(params.src)}`);
            if (params.macAddress) queryParams.push(`macAddress=${encodeURIComponent(params.macAddress)}`);
            if (params.deviceId) queryParams.push(`deviceId=${encodeURIComponent(params.deviceId)}`);
            if (params.channelId) queryParams.push(`channelId=${encodeURIComponent(params.channelId)}`);
            if (params.timestamp) queryParams.push(`timestamp=${encodeURIComponent(params.timestamp)}`);
            if (params.sign) queryParams.push(`sign=${encodeURIComponent(params.sign)}`);
            if (params.sign_ver) queryParams.push(`sign_ver=${encodeURIComponent(params.sign_ver)}`);
            
            const queryString = queryParams.join('&');
            
            // 构建明文 URL Scheme
            let scheme = `weixin://dl/business/?appid=${appId}&path=${path}`;
            
            // 添加 query 参数（如果有）
            if (queryString) {
                scheme += `&query=${encodeURIComponent(queryString)}`;
            }
            
            console.log('========== URL Scheme 生成 ==========');
            console.log('appId:', appId);
            console.log('path:', path);
            console.log('原始query参数:', params);
            console.log('编码前的query字符串:', queryString);
            console.log('完整的URL Scheme:', scheme);
            console.log('=====================================');
            
            try {
                // 尝试打开小程序
                window.location.href = scheme;
                
                // 提示用户
                showStatus('🚀 正在跳转到微信小程序...<br><br>📱 请在小程序中观看广告即可获得60分钟免费WiFi', 'success');
                
                // 备用方案：如果3秒后还在当前页面，给出提示
                setTimeout(() => {
                    showStatus('⚠️ 未能自动跳转，请手动操作：<br><br>1. 打开微信APP<br>2. 搜索小程序"腾途旅途乐"<br>3. 进入后观看广告即可上网', 'error');
                }, 3000);
            } catch (error) {
                console.error('打开小程序失败:', error);
                showStatus('打开小程序失败，请手动打开微信小程序', 'error');
            }
        }

        // 处理开始按钮点击
        function handleStart() {
            // 检查按钮是否被禁用
            const startBtn = document.getElementById('startBtn');
            if (startBtn.disabled) {
                showStatus('⚠️ 您当前无法使用临时上网功能，请稍后再试或观看广告获取正常上网权限', 'error');
                return;
            }
            
            startBtn.disabled = true;
            
            // 显示加载提示
            showLoading('正在打开小程序...');
            
            // 延迟打开小程序，让用户看到加载状态
            setTimeout(() => {
                openMiniProgram();
            }, 500);
            
            // 延迟恢复按钮状态
            setTimeout(() => {
                startBtn.disabled = false;
            }, 3000);
        }

        // 初始化用户认证状态
        async function initUserAuth() {
            try {
                const params = getUrlParams();
                console.log('初始化认证状态，URL参数:', params);

                // 验证必要参数
                if (!params.deviceId || !params.macAddress || !params.timestamp) {
                    console.warn('缺少必要参数，跳过初始化');
                    return;
                }

                // 构建要提交的数据
                const data = {
                    deviceId: params.deviceId,
                    macAddress: params.macAddress,
                    timestamp: params.timestamp
                };

                console.log('调用初始化接口，数据:', data);

                // 调用后端API
                const response = await fetch('/prod-api/OpenPlatform/Income/initUserAuth', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();
                console.log('初始化结果:', result);

                if (result.code === 200) {
                    if (result.alreadyExists) {
                        console.log('用户认证记录已存在且未过期');
                    } else {
                        console.log('初始化用户认证成功:', result.data);
                    }
                } else {
                    console.error('初始化失败:', result.msg);
                }
            } catch (error) {
                console.error('初始化认证状态时发生错误:', error);
            }
        }

        // 页面加载完成后的初始化
        window.addEventListener('DOMContentLoaded', function() {
            const params = getUrlParams();
            console.log('页面加载，URL参数:', params);
            
            // 从后端获取的数据（通过Thymeleaf传递）
            /*[# th:if="${deviceId != null && deviceId != ''}"]*/
            console.log('后端传递的deviceId:', /*[[${deviceId}]]*/ '');
            /*[/]*/
            
            // 检查是否被限制
            /*[# th:if="${isLimited}"]*/
            console.log('🚫 用户触发防刷限制，封禁时长:', /*[[${banDuration}]]*/ '分钟');
            showStatus('⚠️ 您在短时间内使用临时上网次数过多，请 ' + /*[[${banDuration}]]*/ '分钟后再试，或观看广告获取正常上网权限', 'error');
            /*[/]*/
            
            // 可以在这里添加参数验证逻辑
            if (!params.deviceId) {
                showStatus('缺少必要的设备参数', 'error');
                document.getElementById('startBtn').disabled = true;
            } else {
                // 自动调用初始化接口（仅当未被限制时）
                /*[# th:if="${!isLimited}"]*/
                initUserAuth();
                /*[/]*/
            }
        });
    </script>
</body>
</html>

